package com.zhuky.rabbit.producer;

import com.zhuky.rabbit.mapper.MessageLogMapper;
import com.zhuky.rabbit.model.MessageLog;
import com.zhuky.rabbit.constant.Constants;
import com.zhuky.rabbit.model.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.Date;

/**
 * 订单消息发送者
 *
 * @author zhu
 */
@Slf4j
@Component
public class RabbitOrderSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MessageLogMapper messageLogMapper;
    /**
     * step 3：回调函数：confirm确认
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {

        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            log.info("CorrelationData={}", correlationData);
            if (ack) {
                String messageId = correlationData.getId();
                messageLogMapper.changeBrokerMessageLogStatus(messageId, Constants.ORDER_SEND_SUCCESS, new Date());
            } else {
                log.error("Confirm确认失败，请重试或检查MQ状态:{}", cause);
            }
        }
    };



    /**
     * MQ的发送核心方法
     * @param order
     * @throws Exception
     */
    public void send(Order order) throws Exception {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.convertAndSend(
                "order-exchange",
                "order.abcd",
                order,
                new CorrelationData(order.getMessageId())
        );
    }
}
